package be.bonamis.timesheet.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import be.bonamis.timesheet.dto.ProjectDTO;
import be.bonamis.timesheet.model.Project;
import be.bonamis.timesheet.repository.ProjectRepository;
import be.bonamis.timesheet.service.PersonNotFoundException;
import be.bonamis.timesheet.service.ProjectNotFoundException;
import be.bonamis.timesheet.service.ProjectService;

/**
 * This implementation of the ProjectService interface communicates with the
 * database by using a Spring Data JPA repository.
 * 
 * @author Florent Bonamis
 */
@Service
public class RepositoryProjectService implements ProjectService {

	@Resource
	private ProjectRepository projectRepository;

	private static final Logger LOGGER = LoggerFactory
			.getLogger(RepositoryProjectService.class);

	@Transactional
	@Override
	public Project create(ProjectDTO created) {
		LOGGER.debug("Creating a new project with information: " + created);

		Project project = Project.getBuilder(created.getName()).build();

		return projectRepository.save(project);
	}

	@Transactional(rollbackFor = ProjectNotFoundException.class)
	@Override
	public Project delete(Long projectId) throws ProjectNotFoundException {
		LOGGER.debug("Deleting project with id: " + projectId);

		Project deleted = projectRepository.findOne(projectId);

		if (deleted == null) {
			LOGGER.debug("No project found with id: " + projectId);
			throw new ProjectNotFoundException();
		}

		projectRepository.delete(deleted);
		return deleted;
	}

	@Transactional(readOnly = true)
	@Override
	public List<Project> findAll() {
		LOGGER.debug("Finding all projects");
		return projectRepository.findAll();
	}

	@Transactional(readOnly = true)
	@Override
	public Project findById(Long id) {
		LOGGER.debug("Finding project by id: " + id);
		return projectRepository.findOne(id);
	}

	@Transactional(rollbackFor = PersonNotFoundException.class)
	@Override
	public Project update(ProjectDTO updated) throws ProjectNotFoundException {
		LOGGER.debug("Updating person with information: " + updated);

		Project project = projectRepository.findOne(updated.getId());

		if (project == null) {
			LOGGER.debug("No person found with id: " + updated.getId());
			throw new ProjectNotFoundException();
		}

		project.update(updated.getName());

		return project;
	}

}
